<?php
class IndexController extends BaseApiController
{

    function init()
    {
        parent::init();
    }

    #获取手机验证码
    function getCodeAction(){
        $mobile = isset($_REQUEST['mobile']) ? addslashes(htmlspecialchars(trim($_REQUEST['mobile']))): '';

        if(!empty($mobile) && preg_match("/1\d{10}$/", $mobile)) {

//            #测试专用
//            if($mobile == 17621372073){
//                $updArray['updated_at'] = time();
//                $reg_mobile = new UserRegMobileModel();
//                $reg_mobile->updateData($updArray, 1);
//                return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE);
//            }
//
//            #测试专用
//            if($mobile == 18516556253){
//                $updArray['updated_at'] = time();
//                $reg_mobile = new UserRegMobileModel();
//                $reg_mobile->updateData($updArray, 7);
//                return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE);
//            }

            $reg_mobile = new UserRegMobileModel();
            $mobile_code = $reg_mobile->sendCode($mobile);
            if($mobile_code < 0 ){
                $code = 20059; //短信发送过于频繁
                $msg = $this->_error_msg->system_errors[$code];
                return $this->echo_message($msg,$code);
            }

            $Alibaba_new = new AliyunSendMsg();
            $data = array(
                'mobile' => $mobile,
                'code' => $mobile_code,
            );
            $ret = $Alibaba_new->alibaba($data);
            return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE);
        } else {
            #手机号错误
            $code = 20016; //手机号格式不对
            $msg = $this->_error_msg->system_errors[$code];
            return $this->echo_message($msg,$code);
        }
    }


    #注册/登录
    function loginAction(){
        $mobile = !empty($_REQUEST['mobile']) ? intval($_REQUEST['mobile']) : 0;
        $code = !empty($_REQUEST['code']) ? intval($_REQUEST['code']) : 0;
        $type = !empty($_REQUEST['platform_type']) ? intval($_REQUEST['platform_type']) : '3'; //设备类型，1-iOS，2-安卓， 3-未知
        $from = isset($_REQUEST['from']) ? ($_REQUEST['from']) : '';
        $friend_id = isset($_REQUEST['friend_id']) ? intval($_REQUEST['friend_id']) : ''; //邀请好友uid
        $date_id = isset($_REQUEST['date_id']) ? intval($_REQUEST['date_id']) : ''; //聚会ID


        $curtime = time();
        $visit_ip = $this->getIP();

        if(empty($mobile) || empty($code)){
            $code = 10010; //缺少参数
            $msg = $this->_error_msg->system_errors[$code];
            return $this->echo_message($msg,$code);
        }

        #检查验证码
        $user_regmobile_model = new UserRegMobileModel();
        $check_mobile_code = $user_regmobile_model->checkMobileCode($mobile,$code);
        if(!$check_mobile_code){
            $return_code = 20027;//手机和验证码不匹配
            $msg = $this->_error_msg->system_errors[$return_code];
            return $this->echo_message($msg,$return_code);
        }

        #通过手机号获取用户所有信息
        $access_token_obj = new AccessTokenModel();
        $user_model = new UserModel();
        $user_info = $user_model->getUserInfoByMobile($mobile);

        if(empty($user_info)){
            #注册
            $user_info = [
                'nickname' => $mobile,
                'mobile' => $mobile,
                'regtime' => time(),
                'lastvisit' => time(),
                'type' => $type,
                'app_version' => !empty($_REQUEST['app_version']) ? $_REQUEST['app_version'] : '',
                'remote_ip' => $visit_ip,
                'model' => !empty($_REQUEST['model']) ? $_REQUEST['model'] : '',
                'version' => !empty($_REQUEST['version']) ? $_REQUEST['version'] : '',
                'bundle_id' => !empty($_REQUEST['bundle_id']) ? $_REQUEST['bundle_id'] : '',
                'access_token' => $access_token_obj->generateToken(),
            ];
            $uid = $user_model->addData($user_info);
            if(!empty($uid)){
                $user_info['uid'] = $uid;
            }else{
                $return_code = 20013;//注册失败
                $msg = $this->_error_msg->system_errors[$return_code];
                return $this->echo_message($msg,$return_code);
            }

            #查看是否是好友邀请或者聚会邀请,若是,直接成为好友,并且加入聚会
            if(!empty($from) && !empty($friend_id)){

                $friend_info = $user_model->getUserInfoByUid($friend_id);
                if(!empty($friend_info)){
                    $user_list_model = new UserListModel();
                    $user_list_model->makeFriends($uid, $friend_info['uid']);
                }

                if(!empty($date_id)){ //有聚会邀请
                    $date_records_model = new DateRecordsModel();
                    $date_info = $date_records_model->getDataById($date_id);
                    if(!empty($date_info) && $date_info['status'] == 1){
                        $appoint_info = array(
                            'date_id' => $date_id,
                            'uid' => $uid,
                            'promoter' => $uid,
                            'destination' => $date_info['destination'],
                            'longitude' => $date_info['longitude'],
                            'latitude' => $date_info['latitude'],
                            'expired_at' => $date_info['expired_at'],
                            'created_at' => time()
                        );
                        $appointment_model = new AppointmentModel();
                        $appointment_model->addData($appoint_info);
                    }elseif(!empty($date_info) && $date_info['status'] == 2){
                        $user_info['notice'] = "好友约会已取消或结束,赶紧来试试自己发起一个约会吧";//弹窗通知
                    }
                }
            }

        }else{
            #清除原来的token缓存
            $access_token_obj->clearAccessToken($user_info['access_token']);
            $access_token_obj->clearAccessToken('zchDb1Bre1JrEcdstYiiRTGZEJsLRNSX');

            #更新用户最后访问时间
            $update_data = array(
                'access_token' => $access_token_obj->generateToken(),           #更换token
                'lastvisit' => $curtime,
                'remote_ip' => $visit_ip,
            );
            $user_model->updateData($update_data, $user_info['uid']);
            $user_info['access_token'] = $update_data['access_token'];
        }

        if(!empty($user_info['avatar'])){
            $user_info['avatar'] = QINIU_DOMAIN . $user_info['avatar'];
        }
        #设置access_token
        $user_info['access_token'] = $access_token_obj->catcheAccessToken($user_info['uid'], $user_info['access_token']);
        return $this->echo_message(self::RETURN_SUCCESS_MSG,self::RETURN_SUCCESS_CODE,$user_info);
    }


    #推送
    function pushAction(){
        $condition = array();
        $curtime = time();

        $push_model = new PushModel();   //推送表
        $response_data = $push_model->getPushData($condition);

        if(!empty($response_data['forever'])){
            foreach($response_data['forever'] as $key => $val){
                $response_data['forever'][$key]['time'] = date('Y-m-d H:i:s', $val['time']);
                if($val['time'] < $curtime){    //推送时间小于当前时间
                    $day = date('Y-m-d', $val['time']);
                    $min = $val['time'] - strtotime($day);
                    $time = strtotime(date('Y-m-d', $curtime)) + $min;
                    if($time < $curtime){
                        $time = strtotime(date('Y-m-d', $curtime+86400)) + $min;
                    }
                    $response_data['forever'][$key]['time'] = date('Y-m-d H:i:s', $time);
                }
            }
        }

        if(!empty($response_data['once'])){
            foreach($response_data['once'] as $key1 => $val1){
                $response_data['once'][$key1]['time'] = date('Y-m-d H:i:s', $val1['time']);
            }
        }

        return $this->echo_message(self::RETURN_SUCCESS_MSG, self::RETURN_SUCCESS_CODE, $response_data);
    }


}